import 'dart:convert';
import 'dart:typed_data';

import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:fast_rsa/fast_rsa.dart' as f_rsa;
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:flutter/services.dart';

Future<f_rsa.KeyPair> generateRSAKeys() async {
  return await f_rsa.RSA.generate(2048);
}

/// https://blog.csdn.net/bachelores/article/details/126899469
@deprecated
Future<String> decodeByPrivateKey(String privateKeyPemStr, String ciphertext) async {
  var result = decodeByPrivateKeySync(privateKeyPemStr, ciphertext);
  return Future(() => result);
}

String decodeByPrivateKeySync(String privateKeyPemStr, String ciphertext)  {
  final privatePem = privateKeyPemStr;
  RSAPrivateKey privateKey = RSAKeyParser().parse(privatePem) as RSAPrivateKey;
  final encrypter  = Encrypter(RSA(privateKey: privateKey));
  Uint8List cipherBytes = base64.decode(ciphertext);
  var encrypted = Encrypted(Uint8List.fromList(cipherBytes));
  return encrypter.decrypt(encrypted);
}

/// 公钥加密
// Future<String> encodeByPublic(String publicKey, String text){
//   RSAPublicKey rsaPublicKey = RSAKeyParser().parse(publicKey) as RSAPublicKey;
//   final encrypter  = Encrypter(RSA(publicKey: rsaPublicKey));
//   var encrypt = encrypter.encrypt(text);
//   var res = encrypt.base64;
//   return Future(() => res);
// }

